#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

#define PORT 8888
#define BUF_SIZE 1024

int main()
{
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0)
    {
        perror("socket failed");
        exit(1);
    }
    struct sockaddr_in addr, client_addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = INADDR_ANY;
    socklen_t addr_len = sizeof(client_addr);

    if (bind(server_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        perror("bind failed");
        close(server_fd);
        exit(1);
    }

    if (listen(server_fd, 1) < 0)
    {
        perror("listen failed");
        close(server_fd);
        exit(1);
    }
    printf("等待客户端连接...\n");

    int client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
    if (client_fd < 0)
    {
        perror("accept failed");
        close(server_fd);
        exit(1);
    }

    char buff[BUF_SIZE] = {0};
    int len = recv(client_fd, buff, BUF_SIZE - 1, 0);
    if(len > 0)
    {
        buff[len] = '\0';
        printf("Reveived from client: %s\n", buff);
    }
    else if(len == 0)
    {
        printf("client disconnect");
        close(client_fd);
    }
    else
    {
        perror("recv failed");
    }

    close(server_fd);
    close(client_fd);
    return 0;
}

